﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyHandler
{
    public class ValidateCodeHandler : System.Web.IHttpHandler,
            System.Web.SessionState.IRequiresSessionState
    {
        private static System.Random random = new Random();
        public void ProcessRequest(System.Web.HttpContext context)
        {
            context.Response.ContentType = "image/jpeg";

            System.Drawing.Image image = new System.Drawing.Bitmap(60, 30);

            // 生成随机数
            int code = random.Next(1000, 10000);
            string codeString = code.ToString();

            // 使用会话状态
            context.Session["Code"] = codeString;

            using (System.Drawing.Graphics g
                = System.Drawing.Graphics.FromImage(image))
            {
                g.Clear(System.Drawing.Color.WhiteSmoke);
                System.Drawing.StringFormat sf
                    = new System.Drawing.StringFormat();
                sf.Alignment = System.Drawing.StringAlignment.Center;
                sf.LineAlignment = System.Drawing.StringAlignment.Center;
                g.DrawString(
                    codeString,
                    new System.Drawing.Font("Arial", 14),
                    System.Drawing.Brushes.Blue,
                    new System.Drawing.RectangleF(0, 0,
                        image.Width, image.Height),
                    sf
                    );
            }

            context.Response.ContentType = "image/jpeg";
            image.Save(
                context.Response.OutputStream,
                System.Drawing.Imaging.ImageFormat.Jpeg
            );

        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


}
